package com.zbkj.crmeb.merchant.admin.controller;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.crmeb.chant.model.ChannelMerchantRenewal;
import com.zbkj.crmeb.chant.service.ChannelMerchantRenewalService;
import com.zbkj.crmeb.system.model.SystemAdmin;
import org.springframework.beans.factory.annotation.Autowired;

import com.common.CheckAdminToken;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.util.StringUtil;
import com.crmeb.core.utils.RedisUtil;
import com.zbkj.crmeb.system.service.SystemAdminService;

import cn.hutool.core.util.StrUtil;

import java.util.Date;

/**
 * @author cyz
 * @date 2021年05月19日15:27
 */
public class AdminBaseController {
    @Autowired
    CheckAdminToken checkAdminToken;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    SystemAdminService systemAdminService;
    @Autowired
    private ChannelMerchantRenewalService channelMerchantRenewalService;

    public Integer getMerId(HttpServletRequest request){
        String token = checkAdminToken.getTokenFormRequest(request);
        if(StringUtil.isEmpty(token)){
            throw new CrmebException("token已失效,请重新登录!");
        }
        Object merId = redisUtil.get(StrUtil.format(Constants.ADMIN_TOKEN_MER_KEY, token));
        if(null == merId) {

            SystemAdmin admin = systemAdminService.lambdaQuery().eq(SystemAdmin::getNowToken, token).one();
            if(null == admin || admin.getIdentityType() != 1){
                // 用户未绑定商户提示
                throw new CrmebException("当前用户未绑定商户, 请先绑定所属商户!");
            }
            // 表示总后台超级管理员
            return null;

        }
        // 校验商户剩余使用时间
		/*SystemAdmin systemAdmin = systemAdminService.getInfo();
		if(systemAdmin.getIdentityType() == 2){
		    ChannelMerchantRenewal merchantRenewal = channelMerchantRenewalService.getOne(Wrappers.<ChannelMerchantRenewal>lambdaQuery()
		            .eq(ChannelMerchantRenewal::getMerId, Integer.parseInt(merId.toString()))
		            .orderByDesc(ChannelMerchantRenewal::getId).last("LIMIT 1"));
		    if(merchantRenewal == null || merchantRenewal.getExpirationTime().before(new Date())){
		        throw new CrmebException("您的后台使用期限已到，请联系平台进行续费");
		    }
		}*/
        return Integer.parseInt(merId.toString());
    }
    
    /**
     * 未取到不会报错(代理商全部商户场景)
     * @author daigb
     * @date:  2022-06-06 18:41
     */
    public Integer getMerIdByNull(HttpServletRequest request){
    	String token = checkAdminToken.getTokenFormRequest(request);
    	if(StringUtil.isEmpty(token)){
    		throw new CrmebException("token已失效,请重新登录!");
    	}
    	Object merId = redisUtil.get(StrUtil.format(Constants.ADMIN_TOKEN_MER_KEY, token));
    	if(null != merId) {
        	return Integer.parseInt(merId.toString());
    	}
    	
    	return null;
    }
    
}
